package com.tceasy.gateway.service

import com.tceasy.gateway.dao.DeveloperDao
import com.tceasy.gateway.dao.ServiceDao
import com.tceasy.gateway.domain.OpenDeveloper
import com.tceasy.gateway.domain.OpenService
import org.apache.commons.lang.StringUtils
import org.bson.BSONObject
import org.bson.util.JSON
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.Assert
/**
 * Created by zhanghuan on 2016/4/11.
 */
@Service
class MethodService {

    Logger logger=LoggerFactory.getLogger(MethodService.class)

    @Autowired
    ServiceDao serviceDao
    @Autowired
    DeveloperDao developerDao
    static pageSize=20

    /**
     * 添加接口
     * @param openService
     */
    public void add(OpenService openService){
        logger.info("========添加接口开始{}",openService)
        Assert.notNull(openService,"参数错误")
        String method=openService.getMethod()
        Assert.hasText(method,"接口路径不能为空")
        Assert.hasText(openService.getUrl(),"url不能为空")
        Assert.hasText(openService.getParamTemplate(),"参数模板不能为空")
        Assert.hasText(openService.getName(),"接口名称不能为空")
        Assert.isNull(serviceDao.findOneByPk(method),"接口已存在")
        openService.setCreateTime(new Date())
        openService.setLastModifyTime(new Date())
        serviceDao.insert(openService)
    }

    /**
     * 删除接口
     * @param method
     */
    public void delete(String method){
        logger.info("==========删除接口：{}开始",method)
        Assert.hasText(method,"接口标识不能为空")
        Assert.notNull(serviceDao.findOneByPk(method),"该接口不存在")
        /*查询所有拥有此接口权限的开发者，如果有，则提示先解除所有授权此接口访问的开发者*/
        List<OpenDeveloper> developers=developerDao.findAll(["permission.method":method],null);
        if(developers==null||developers.isEmpty()){
            serviceDao.deleteByPk(method)
        }else{
            throw new RuntimeException("先解除所有此接口的授权再删除");
        }
    }

    /**
     * 开启接口
     * @param method
     */
    public void open(String method){
        logger.info("=========开启{}接口",method)
        Assert.hasText(method,"接口路径不能为空")
        OpenService openService=serviceDao.findOneByPk(method)
        Assert.notNull(openService,"接口不存在")
        serviceDao.updateByPk(method,"state","Y")
    }

    /**
     * 关闭接口
     * @param method
     */
    public void close(String method){
        logger.info("==========关闭{}接口",method)
        Assert.hasText(method,"接口路径不能为空")
        OpenService openService=serviceDao.findOneByPk(method)
        Assert.notNull(openService,"接口不存在")
        serviceDao.updateByPk(method,"state","N")
    }

    /**
     * 根据method更新记录
     * @param method 接口路径
     * @param service 需要修改的字段以及修改成的值，不需修改的field不要出现在此参数中
     */
    public void update(String method,OpenService service){
        logger.info("=========修改{}接口，修改参数：{}",method,service)
        Assert.hasText(method,"接口路径不能为空")
        Map modifier=[:]
        OpenService.metaClass.properties.each {
            if(!StringUtils.equals("class",it.name)&&null!=service."${it.name}"){
                modifier.put(it.name,service."${it.name}")
            }
        }
        modifier.put("lastModifyTime",new Date())
        serviceDao.updateByPk(method,modifier)
    }

    /**
     * 根据主键查询
     * @param method
     * @return
     */
    public OpenService findOne(String method){
        return serviceDao.findOneByPk(method);
    }

    /**
     * 分页查询(每页20条)
     * @param matcher 查询条件，json格式
     * @param orderBy 排序规则1代表正序，-1代表倒序 例如{age:-1}根据年龄倒序
     * @param start 第几条开始
     * @return
     */
    public List<OpenService> findByPage(String matcher,String orderBy,Integer start){
        logger.info("=======查询记录开始，matcher:{},orderBy:{},start:{}",[matcher,orderBy,start] as String[])
        return serviceDao.findPerPage((BSONObject) JSON.parse(matcher),(BSONObject) JSON.parse(orderBy),start,pageSize)
    }

    /**
     * 根据条件查询所有记录
     * @param matcher
     * @param orderBy
     * @return
     */
    public List<OpenService> find(String matcher,String orderBy){
        logger.info("=======查询记录开始，matcher:{},orderBy:{}",[matcher,orderBy] as String[])
        return serviceDao.findAll(matcher,orderBy)
    }

    /**
     * 查询符合条件的记录总数
     * @param matcher
     * @return
     */
    public long count(String matcher){
        return serviceDao.count((BSONObject) JSON.parse(matcher))
    }

    /**
     * 查询总页数
     * @param matcher
     * @return
     */
    public int getPageCount(String matcher){
        return serviceDao.getPageCount((BSONObject) JSON.parse(matcher),pageSize)
    }
}
